<template>
  <div>
    <!-- 头部card -->
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="职位搜索:">
          <el-input
            placeholder="请输入搜索职位关键字"
            v-model="keyword"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="keyword ? false : true" @click="search">
            搜索
          </el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 中部card -->
    <el-card style="margin: 10px 0px">
      <el-button icon="puls" @click="addRole">添加角色</el-button>
      <el-table border style="margin: 10px 0px" :data="allRole">
        <el-table-column
          type="selection"
          align="center"
          border
        ></el-table-column>
        <el-table-column
          label="#"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="角色名称"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" style="width: 500px" align="center">
          <template #="{ row, $index }">
            <el-button icon="User" size="small" @click="setPermisstion(row)">
              分配角色
            </el-button>
            <el-button icon="Edit" size="small" @click="updateRole(row)">
              编辑
            </el-button>

            <el-popconfirm
              width="260px"
              :title="`你确定删除${row.roleName}吗?`"
              @confirm="removeRole(row.id)"
            >
              <template #reference>
                <el-button icon="Delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        @current-change="getHasRole"
        @size-change="sizeChange"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
    <!-- 添加职位与更新 对话框-->
    <el-dialog
      v-model="dialogVisite"
      :title="ROleParams.id ? '更新职位' : '添加职位'"
    >
      <el-form :model="ROleParams" :rules="rules" ref="form">
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            placeholder="请你输入职位名称"
            v-model="ROleParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisite = false">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </template>
    </el-dialog>
    <!-- 分配权限抽屉 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <div>
          <el-tree
            ref="tree"
            :data="menuArr"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2, 3]"
            :default-checked-keys="selectArr"
            :props="defaultProps"
          />
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handler">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
//请求方法
import {
  RoleResponseData,
  Records,
  RoleData,
  MenuResponseData,
  MenuList,
} from '@/api/acl/role/type'
import {
  reqRemoveRole,
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermission,
} from '@/api/acl/role'
//引入骨架仓库
import useLayOutSettingStore from '@/store/modules/setting'
import { ElMessage } from 'element-plus'
import { remove } from 'nprogress'
let SettingStore = useLayOutSettingStore()
// 当前页码
let pageNo = ref<number>(1)
//展示数据数量
let pageSize = ref<number>(10)
//搜索职位关键字
let keyword = ref<string>('')
//存储全部已有职位
let allRole = ref<Records>([])
//职位总个数
let total = ref<number>(0)
//控制对话框的显示与隐藏
let dialogVisite = ref<boolean>(false)
//收集新增岗位数据
let ROleParams = reactive<RoleData>({
  roleName: '',
})
//控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
//获取form组件
let form = ref<any>()
//定义数组存储用户权限数据
let menuArr = ref<MenuList>([])
//存储数据节点id
let selectArr = ref<any>([])
//获取tree组件实例
let tree = ref<any>()
//组件挂载
onMounted(() => {
  //获取职位请求
  getHasRole()
})
//获取全部用户信息
const getHasRole = async (pager = 1) => {
  //修改当前页码
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}
//下拉菜单回调
const sizeChange = () => {
  getHasRole()
}
//搜索按钮回调
const search = () => {
  getHasRole()
  keyword.value = ''
}
//重置按钮回调
const reset = () => {
  SettingStore.refsh = !SettingStore.refsh
}
// 添加职位回调
const addRole = () => {
  dialogVisite.value = true
  Object.assign(ROleParams, {
    roleName: '',
    id: 0,
  })
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//更新职位回调
const updateRole = (row: RoleData) => {
  dialogVisite.value = true
  Object.assign(ROleParams, row)
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//职位校验规则
const validatorRoleName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('职位名称至少两位'))
  }
}
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
//确定按钮回调
const save = async () => {
  await form.value.validate()
  let result: any = await reqAddOrUpdateRole(ROleParams)
  if (result.code == 200) {
    ElMessage({
      type: 'succes',
      message: ROleParams.id ? '更新成功' : '添加成功',
    })
    dialogVisite.value = false
    getHasRole(ROleParams.id ? pageNo.value : 1)
  }
}
//删除已有职位
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code == 200) {
    ElMessage({ type: 'succes', message: '删除成功' })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
//设置权限按钮回调
const setPermisstion = async (row: RoleData) => {
  drawer.value = true
  Object.assign(ROleParams, row)
  let result: MenuResponseData = await reqAllMenuList(ROleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
//树形控件
const defaultProps = {
  children: 'children',
  label: 'name',
}

const filterSelectArr = (allDate: any, initArr: any) => {
  allDate.forEach((item: any) => {
    if (item.select && item.level == 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
}
// 抽屉确定按钮的回调
const handler = async () => {
  const roleId = ROleParams.id as number
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let result: any = await reqSetPermission(roleId, permissionId)
  if (result.code == 200) {
    ElMessage({ type: 'succes', message: '分配成功' })
    window.location.reload()
  }
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
